﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;

namespace ClockSync2
{
    class tcpClient
    {
        public TcpClient tcpclnt;
        public IPAddress IP;
        public int port;
        NetworkStream stm;
        ASCIIEncoding asen;

        public tcpClient(IPAddress ip, int port)
        {
            Console.WriteLine("in tcpClient constructor ip: " + ip.ToString() + " port: " + port);
            try
            {
                tcpclnt = new TcpClient();
                
                Console.WriteLine("tcpClient, connecting...");
                tcpclnt.Connect(ip, port); // use the ipaddress as in the server program

                stm = tcpclnt.GetStream();
                asen = new ASCIIEncoding();
                
                this.IP = ip;
                this.port=port;
                Console.WriteLine("connected");
            }
            catch (Exception e)
            {
                Console.WriteLine("Error in TCPClient on IP: "+ IP.ToString() + ":"+port+"\n" + e.StackTrace);
            }
        }

        public void open(IPAddress ip, int port)
        {
            Console.WriteLine("in tcpClient constructor ip: " + ip.ToString() + " port: " + port);
            try
            {
                tcpclnt = new TcpClient();
                Console.WriteLine("tcpClient, connecting...");
                tcpclnt.Connect(ip, port); // use the ipaddress as in the server program
                this.IP = ip;
                this.port = port;
                Console.WriteLine("connected");
            }
            catch (Exception e)
            {
                Console.WriteLine("Error..... " + e.StackTrace);
            }
        }

        public void exit()
        {
            tcpclnt.Close();
            stm.Close();
        }

        public void sendMsg(String msg)
        {
            Console.WriteLine("in tcpServer sending " + msg + " to " + IP.ToString());
            byte[] word = asen.GetBytes(msg);
            stm.Write(word, 0, word.Length);
            Console.WriteLine("msg sent");
            //stm.Flush();
        }

    }
}
